// pages/seeOrder/seeOrder.js
const app = getApp()
import Api from '../../utils/api';
import util from '../../utils/util';
let wxbarcode = require('../../utils/index.js');
// var trimer;
Page({

  /**
   * 页面的初始数据
   */

  data: {
    trimer:null,
    //未支付 UNPAY,
    //已支付 拼团中  PAYED,
    //待发货  WAITSEND,
    //已发货  SENDED,
    //待评价 WAITCOMMENT,
    //已完成 ACCOMPLISH,
    //已取消 CONCEL,
    loginFlag: false,
    orderStatus: ["PAYED", "UNPAY", "WAITSEND", "SENDED", "WAITCOMMENT", "ACCOMPLISH", "CONCEL"],
    orderStatusText: ['拼团中', '待付款', '待接单', '待收货', '待评价', '已完成', '已取消'],
    orderStatusIndex: 0,
    page: 1,
    size: 10,
    dataList: [],
    barcodeModeal: false,
    code: '',
    showOrderDetail: false,
    orderItem: {},
    address: {},
    istemplate: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this
    if (options.orderStatusIndex != undefined) {
      _this.setData({
        orderStatusIndex: options.orderStatusIndex
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let _this = this;
    _this.queryOrder();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let _this = this;
    _this.isProductRelease();
    if (this.data.loginFlag) {
      _this.queryOrder();
      _this.setData({
        loginFlag: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log("onHide",this.data.trimer);
    if (this.data.trimer) {
      clearInterval(this.data.trimer);
      this.setData({
      trimer:null,
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("onHide", this.data.trimer);
    if (this.data.trimer) {
      clearInterval(this.data.trimer);
      this.setData({
        trimer: null,
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    //console.log("上拉刷新")
    let _this = this;
    _this.setData({
      page: 1,
      dataList: [],
    })
    wx.showLoading({
      title: '刷新中',
    })
    _this.queryOrder(function() {
      setTimeout(function() {
        wx.hideLoading()
      }, 2000)
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    //console.log("下拉加载")
    let _this = this;
    if (_this.data.page < _this.data.totalPages) {
      _this.setData({
        page: _this.data.page + 1,
      })
      wx.showLoading({
        title: '加载中',
      })
      _this.queryOrder(function() {
        setTimeout(function() {
          wx.hideLoading()
        }, 2000)
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    app.globalData.otherPageHideFlag = true;
  },

  //查询订单
  queryOrder(callback) {
    let _this = this;
    let data = {
      orderStatus: _this.data.orderStatus[_this.data.orderStatusIndex],
      sort: "desc"
    }
    console.log(data)
    Api.queryOrder(data, _this.data.page, _this.data.size).then(res => {
      let list = res.data.dataList;
      console.log(list)

      //预执行支付有效期倒计时
      if (_this.data.orderStatusIndex == 1) {
        for (var i = 0; i < list.length; i++) {
          var orderItem = list[i];
          let formatData = util.getTimeLeft(orderItem.order.orderTime + 7200000);
          if ((typeof formatData != 'number')) {
            let formatDataStr = formatData.hours + ":" + formatData.minutes + ":" + formatData.seconds;
            orderItem.order.formatData = formatDataStr;
          } else {
            orderItem.order.formatData = null;
          }
        }
      }
      _this.setData({
        dataList: _this.data.dataList.concat(res.data.dataList),
        totalPages: res.data.totalPages
      });
      console.log(_this.data.dataList);
      //执行循环取消订单
      setTimeout(() => {
        _this.orderInterval();
      }, '800');
      (callback && (typeof callback) === "function") && callback();
    })
  },

  //tab切换中
  tabClick(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    console.log(index);
    _this.setData({
      orderStatusIndex: index,
      dataList: [],
      page: 1,
    });
    _this.queryOrder();
  },
  //取消订单
  cancelOrder(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    Api.cancelOrder(_this.data.dataList[shopindex].order.id).then(res => {
      wx.showToast({
        title: '取消成功!',
        icon: 'none',
        duration: 1500,
      })
      //console.log(res)
      let arr = _this.data.dataList;
      arr.splice(shopindex, 1)
      _this.setData({
        dataList: arr
      })
    })
  },

  //待付款订单继续支付
  payOrder(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let arr = _this.data.dataList;
    Api.payOrder(arr[shopindex].order.id).then(res => {
      //console.log(res)
      console.log("待付款订单继续支付", res)
      let payString = JSON.parse(res.data.payString);
      wx.requestPayment({
        timeStamp: payString.timeStamp,
        nonceStr: payString.nonceStr,
        package: payString.package,
        signType: payString.signType,
        paySign: payString.paySign,
        success(res) {
          arr.splice(shopindex, 1)
          _this.setData({
            dataList: arr
          })
        },
        fail(res) {

        },
        complete(res){
          console.log('seeOrder.js==========调用了微信支付页面complete')
          app.globalData.otherPageHideFlag = true;
        }
      })
    })
  },

  //确认订单
  confirmOrder(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    Api.confirmOrder(_this.data.dataList[shopindex].order.id).then(res => {
      wx.showToast({
        title: '确认成功!',
        icon: 'none',
        duration: 1500
      });
      let arr = _this.data.dataList;
      arr.splice(shopindex, 1)
      _this.setData({
        dataList: arr
      })
    })
  },

  showBarcodeModeal(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    console.log(_this.data.dataList[index])
    if (_this.data.orderStatusIndex == 2 && (_this.data.dataList[index].order.deliveryType == "ZT" || _this.data.dataList[index].order.deliveryType == "CONSUME")) {
      _this.setData({
        barcodeModeal: true,
        code: _this.data.dataList[index].order.orderCode
      });
      wxbarcode.barcode('barcode', _this.data.code, 680, 200); //YCM91128 生成条形码
    }
  },
  //关闭点击弹出红包的条形码模态框开始
  closebarcodeModeal(e) {
    this.setData({
      barcodeModeal: false
    });
  },
  //跳转店铺
  toShopPage(e) {
    console.log('店铺跳转', e);
    let order = e.currentTarget.dataset.order;
    let shop = e.currentTarget.dataset.shop;
    if (order.orderTableType != 'COMMON_ORDER') {
      //跳转拼团列表
      wx.navigateTo({
        url: '/pages/activityList/activityList',
      })
    } else {
      //跳转店铺
      wx.navigateTo({
        url: `/pages/shopClass/shopClass?id=${shop.id}`,
      })
    }
  },
  //商品详情跳转
  toGoodsDesc(e) {
    console.log('商品跳转', e);
    let type = e.currentTarget.dataset.type;
    let item = e.currentTarget.dataset.item;
    if (type != 'COMMON_ORDER') {
      wx.showToast({
        icon: 'none',
        title: '拼团商品不能进入详情',
      })
    } else {
      wx.navigateTo({
        url: `/pages/details/shopDetail?id=${item.goodsId}`,
      })
    }
  },
  //查看订单详情
  orderDetail(e) {
    console.log(e)
    let _this = this;
    let order = e.currentTarget.dataset.order;
    console.log(order)
    order.order.orderTime = util.formatTime(new Date(order.order.orderTime));
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?order=' + JSON.stringify(order) + '&orderStatusIndex=' + _this.data.orderStatusIndex,
    })
  },
  //关闭订单详情弹窗
  hideOrderClick() {
    let _this = this;
    _this.setData({
      showOrderDetail: false,
    })
  },
  //判断产品发布信息
  isProductRelease() {
    let _this = this;
    Api.isProductRelease().then(res => {
      console.log('进入标记查询', res)
      _this.setData({
        istemplate: res.data
      })
    }).catch(err => {
      _this.setData({
        istemplate: true
      })
    });
  },

  //跳转到评论页面
  commentSubmit(e) {
    console.log(e.currentTarget.dataset.shopitem);
    let item = JSON.stringify(e.currentTarget.dataset.shopitem);
    wx.navigateTo({
      url: `/pages/commentSubmit/commentSubmit?item=${item}`,
    })
  },
  //开启定时时间处理
  orderInterval() {
    var _this = this;
    if (_this.data.orderStatusIndex != 1) {
      if (_this.data.trimer) {
        clearInterval(_this.data.trimer);
        // trimer = null;
        _this.setData({
          trimer:null
        })
      }
      console.log(`already clear orderInterval:trimer, orderStatusIndex:${_this.data.orderStatusIndex}`);
      return;
    }
    console.log('orderInterval execute!!!');
   var trimer = setInterval(() => {
      var orderList = this.data.dataList;
      for (var i = 0; i < orderList.length; i++) {
        var orderItem = orderList[i];
        let formatData = util.getTimeLeft(orderItem.order.orderTime + 7200000);
        if ((typeof formatData != 'number')) {
          let formatDataStr = formatData.hours + ":" + formatData.minutes + ":" + formatData.seconds;
          orderItem.order.formatData = formatDataStr;
        } else {
          orderItem.order.formatData = null;
        }
      }
      _this.setData({
        dataList: orderList
      });
    }, '1000');
    _this.setData({
      trimer: trimer
    })
  },


})